import React from 'react';
import {observable, action, toJS} from 'mobx';
import {Tools, Bubble, Modal} from 'weaver-mobile';
import { Browser, CKRichText } from 'weaver-mobile-page';
import { ShareAuth, Form, /*Reply*/ } from 'weaver-mobile-page';
import * as API from '../../api/systemdoc';
import isFunction from 'lodash/isFunction';
// import RichText from '../../util/richText';
const getLabel = Tools.getLabel;
const alert = Modal.alert;

export default class AddStore {
  parent = null;
  path = '';//前缀路径
  scope = '';//当前的scope，与categoryId只会同时存在一个
  categoryId = '';//当前的目录（是从哪个目录点添加文档进来的），与scope只会同时存在一个
  saveBackFunc = null;//保存
  constructor({parent, path, scope, categoryId, saveBackFunc}) {
    this.parent = parent;
    this.path = path;
    this.scope = scope;
    this.categoryId = categoryId;
    this.secCategoryBrowser = new Browser.Store({ route: path,id:'secCategoryBrowser'});
    this.form = new Form.Store({route: path});
    this.shareTypeStore = new ShareAuth.Store({route: path, id: 'type'});
    this.saveBackFunc = saveBackFunc;
  }
  
  @observable id = '';// 文档id，现在只在共享页面使用
  
  // @observable text = '';
  @observable addTab = 'content';// 新增页面下的页签, content/property
  @observable pageType = 'choose';// 选择目录页面/文本页面/共享页面，choose/text/share
  @observable form = null;
  // @observable reply = new Reply.Store({ getAttachList: this.getReplyAttachList });
  // replyRef = null;
  @observable loading = false;
  
  @observable defaultShareList = [];//默认共享列表
  @observable nonDefaultShareList = [];//非默认共享列表  
  @observable filterCategoryIdList = "";//选择目录时的过滤目录id列表
  @observable filtertype = "";//选择目录时的过滤目录id列表
  @observable shareCanAdd = false;
  @observable shareCanDelete = false;
  @observable shareCondition = null;
  @observable shareTypeStore = null;
  @observable secCategoryBrowser;
  @observable canCreate = true;//是否有权限新建，无权限时会在目录选择页面显示无权限提示
  @observable canEdit = true;
  
  @observable MenuElliVisible = false;
  @observable hasMenuElli = false;
  @observable menus = [];
  @observable mFileType = ".html";
  @observable isOffice = "0";
  @observable temSaveParam = {};
  @observable off_imagefileid = "";
  @observable mainimagefile="";
  
  @observable richTextStore = new CKRichText.Store({reply:{ getAttachList: this.getReplyAttachList}});
  
  uploadSize = 0;
  uploadType = '';
  docIsSave = true; //判断当前保存文档接口是否执行完毕，执行完毕前不允许再次执行（避免点击多次提交问题）
  fileid = 0;
  
  @action
  // setText = (v) => {
  //   this.text = v;
  // }
  
  appendText = (v) => {
    // this.text = this.text + v;
    this.richTextStore.insertHtml(v);
  }
  setDatas=(params={})=>{
    Object.keys(params).forEach(key=>{
      this[key] = params[key];
    });
    return this;
  }
  @action
  init = () =>{
    // this.text = '';
    this.richTextStore.clear();
    this.addTab = 'content';
    this.defaultShareList = [];
    this.nonDefaultShareList = [];
    this.secCategoryBrowser = new Browser.Store({ route: this.path,id:'secCategoryBrowser'});
    
    if (this.scope) {
      // 获得scope配置
      this.loading = true;
      API.getDefaultCategory({scope: this.scope}).then((result) => {
        if (result && result.categorylist.length === 1) {// 只有一个目录可选时，直接进入目录
          this.pageType = 'text';
          let categoryId = result.categorylist[0].id;
          this.initSecCategory(categoryId);
        } else if(result && result.categorylist){
          result.categorylist.map((val,index)=>{
            return index===0 ? this.filterCategoryIdList = val.id : this.filterCategoryIdList += (","+val.id); 
          });
          this.pageType = 'choose';
          this.filtertype = result.filtertype;
        }
        this.loading = false;
      });
      
      this.loading = true;
      API.getCreateDocType({scope: this.scope,doctype:this.mFileType}).then(action((result) => {
    	if(result && result.editOffice == 1){
    		this.hasMenuElli = true;
    		this.menus = result.typelist; 
    		if(this.mFileType == ".html"){
	    		this.setFileType(".docx");
	  			this.setIsOffice("1");
  			}
    	}
    	this.loading = false;
      }));
      
    } else if (this.categoryId) {
      this.initSecCategory(this.categoryId);
    } else {
      this.pageType = 'choose'
    }
    
  }
  
  /**
   * 初始化目录
   * @param secCategoryId
   */
  @action
  initSecCategory = (secCategoryId) => {
    if (!secCategoryId) {
      return;
    }
    // 获得目录对应的属性配置
    API.getCategoryParamCondition({secid: secCategoryId}).then(action((result) => {
      this.canCreate = result.canCreate;
      if (!result.canCreate) {
        this.pageType = 'choose';
        return;
      }
      this.pageType = 'text';
      // 将返回值转为form的field
      let fields = result.data.map((item, index) => {
        // 记录上传大小与上传类型的限制
        const {paramForm : {domkey}} = item;
        if (Array.isArray(domkey) && domkey.length > 0) {
          const key = domkey[0];
         if (key === 'uploadSize') {
            this.uploadSize = item.paramForm.defaultValue;
          } else if (key === 'uploadType') {
            let type = item.paramForm.defaultValue;
            if (type === '*.*') type = "";
            this.uploadType = type;
          }
        }
        
        if (!item.conditionType && !item.paramForm.conditionType) {
          item.conditionType = 'CUSTOM';
          item.otherCom = (
            <span dangerouslySetInnerHTML={{ __html: item.value }} />
          );
        } else if (item.conditionType === 'CUSTOM' && (item.paramForm.customType === 'INPUT_INT' || item.paramForm.customType === 'INPUT_FLOAT')) {
          item.conditionType = 'INPUTNUMBER';
          // TODO 现在没有组件，先放一个数字组件
          // if (item.paramForm.customType === 'INPUT_INT') {
          //   // 整数
          //   item.type = 'digit';
          // } else {
          //   // 小数，3个小数位
          //   item.type = 'number';
          // }
        }
        let value = item.value || item.paramForm.value || item.paramForm.defaultValue;
        return {colSpan: 1, ...item, ...item.paramForm, value, rules: item.paramForm.mustInput ? 'required' : ''};
      });
      fields.unshift({
        colSpan: 1,
        conditionType: 'INPUT',
        domkey: ['docSubject'],
        label: result.docTitleLabel,
        rules: 'required',
        viewAttr: 3,
        show: true,
      });
      //处理一下，摘要渲染成非必填字段（为了在隐藏摘要的时候，避开必填校验）
      fields.map((val)=>{
        if(val.domkey[0]==="docmain"){
          val.rules = '';
        }
        return val;
      })
      let conditions = [{defaultshow: true, items: fields, show: true, title: getLabel(33197, '文档属性')}],
        route = this.path;
      // 转换配置结束
      // 初始化或重置form
      if (this.form.isInit) {
        this.form.resetConditions(conditions, route);
      } else {
        this.form.initForm(conditions, route);
      }
      // 重置内容
      this.resetContent();
    }));
    
    // 获得目录对应的共享配置
    API.getShareCondition({docid: this.id}).then((result) => {
      this.shareCondition = result.conditions;
    })
  }
  
  
  /**
   * 重置文本内容
   */
  resetContent = () => {
    this.richTextStore.clear();
    this.richTextStore.replyStore.doInit();
    let {selectedPubMouldId} = this.form.formData;
    let pubMouldId = selectedPubMouldId ? selectedPubMouldId.value : '';
    if (pubMouldId) {
      API.getMouldContent({mouldid: pubMouldId}).then((result) => {
        // this.text = result.content;
        this.richTextStore.setRichText(result.content);
      })
    }
  }
  
  setMenuElliVisible = (visible) =>{
  	this.MenuElliVisible = visible;
  }
  setIsOffice = (isOffice) => {
  	this.isOffice = isOffice;
  }
  setFileType = (mFileType) => {
  	this.mFileType = mFileType;
  }
  
  @action
  initEdit = (id,fileid) => {
  	this.pageType = "init";
  	API.getDocFileEdit({id: id,imagefileid:fileid}).then(action((result) => {
	  	this.id = result.id;
	  	this.pageType = "edit";
	  	this.mFileType = result.mFileType;
	  	this.fileid = result.imagefileid;
	  	this.canEdit = result.canEdit;
  	}))
  	
  }
  
  /**
   * 文本页面的保存/草稿
   * @param isDraft
   * @param history
   */
  save = ({isDraft, history} = {isDraft: false}) => {
    let validResult = this.form.doValidate();
    let docPublishType = "";
    let docmain = "";
    if(this.form.formData.docPublishType){
      docPublishType = this.form.formData.docPublishType.value || "";
    }
    if(this.form.formData.docmain){
      docmain = this.form.formData.docmain.value || "";
    }
    if(this.docIsSave){
      if (validResult.pass) {
        if(docPublishType === "2" && docmain===""){
          Bubble.error(getLabel(516296,'摘要未填写'));
        }else{
          let formData = toJS(this.form.formData), params = {};
          for (let key in formData) {
            let v = formData[key].value;
            if (Array.isArray(v)) {
              params[key] = v.map((item) => item.id).join();
            } else {
              params[key] = v;
            }
          }
          let secid = params.seccategory;
          API.isExists({
            secid,
            docSubject: params.docSubject
          }).then((result) => {
            if (result.status === 1) {
              let data = this.richTextStore.getData();
              let {attach: {file}, richText} = data;
              const submitParams = {
                  ...params,
                doccontent: richText ? richText.replace(
                  /<link\s?[^>]+\/spa\/document\/content\.css{1}[^>]+\s?\/>/g, () => ''
                ) : '',
                fileids: Array.isArray(file) ? file.map((item) => item.id).join() : '',
                off_imagefileid:this.off_imagefileid,
                isOffice : this.isOffice,
                mainimagefile:this.mainimagefile,
              };
              submitParams.operate = isDraft ? 'draft' : 'submit';
              this.docIsSave = false;
              API.save(submitParams).then((result) => {
                this.docIsSave = true;
                if (result.blnOsp === '1') {
                  this.pageType = 'share';
                  this.id = result.docid;
                } else {
                  Bubble.success(getLabel(22619, "保存成功"));
                  isFunction(this.saveBackFunc) && this.saveBackFunc({id: result.docid, history});
                }
              })
            } else {
              Bubble.error(result.msg);
            }
          })
        }
      } else {
        Bubble.error(validResult.message);
        this.addTab = 'property';
        window.setTimeout(this.form.doValidate, 0);
      }
    }
    
  }
  
  saveEdit = (params) => {
  	this.saveOffice();
  }
  saveEditAccept = (params) => {
  	//this.loading = true;
  	 API.saveOffice({
  	 	id : this.id,
  	 	oldimagefileid : this.fileid,
  	 	imagefileid : this.off_imagefileid
  	 }).then((result) => {
  	 	//this.loading = false;
  	 	if(result.api_status){
  	 		window.location = result.url;
  	 	}
  	 })
  }
  
  
  saveOffice = (params) => {
  	this.temSaveParam = params;
  	
  	if(!window.acceptSaveMsg){
  		window.acceptSaveMsg = this.acceptSaveMsg.bind(this);
  	}
  	
  	document.getElementById("webOffice").contentWindow.sendSaveMsg();
  }
  
  acceptSaveMsg = () =>{
	let formData = toJS(this.form.formData)
	let isEdit = this.id > 0;
	
   	let obj = document.getElementById("webOffice").contentWindow.toSaveDocument(isEdit ? false : {fileName : formData.docSubject.value});

    if(obj.off_status == 0){
        obj.msg = obj.off_msg ? obj.off_msg : getLabel(84544,'保存失败！');
        Bubble.error(obj.msg);
        return;
    }
    this.off_imagefileid = obj.off_imagefileid;
    if(isEdit){//编辑
    	this.saveEditAccept(this.temSaveParam);
    }else{ //新建
  		this.save(this.temSaveParam);
  	}
  }
  
  /**
   * 切换Tab
   * @param tab
   */
  changeTab = (tab) => {
    this.addTab = tab.key;
  }
  
  // 修改文档编辑模板
  changeSelectedPubMouldId = (field, mobxDatas) => {
    // 编辑时不提示，也不做动作，不过现在没有编辑，就不处理了
    return new Promise((resolve => {
      let previousId = this.form.formData.selectedPubMouldId.value;
      resolve();
      alert(getLabel(131329,'信息确认'), getLabel(81566,'本目录绑定了编辑模板，加载编辑模板可能会导致文档内容丢失，建议先复制下文档内容，确定要继续吗？'),
        [
          { text: getLabel(31129, '取消'), onPress: () => {this.form.updateField('selectedPubMouldId', previousId)}},
          {
            text: getLabel(826, '确定'),
            onPress: this.resetContent
          },
        ]);
    }));
  }
  
  /**
   * 切换目录
   * @param field
   * @param mobxDatas
   * @returns {Promise<any>}
   */
  changeSecCategory = (field, mobxDatas) => {
    return new Promise((resolve => {
      let params = toJS(this.form.formData), datas = toJS(mobxDatas);
      if (datas.length === 0) {return;}
      if (!params.seccategory) {
        resolve();
        this.initSecCategory(datas[0].id);
        return;
      }
      alert(getLabel(131329,'信息确认'), getLabel(81565,'切换目录会清除文档属性和附件，确定要继续吗？'),
        [
          { text: getLabel(31129, '取消'), onPress: () => {}},
          {
            text: getLabel(826, '确定'),
            onPress: () => {
              resolve();
              this.initSecCategory(datas[0].id);
            }
          },
      ]);
    }));
  }
  
  /**
   * 修改发布类型
   * @param field
   * @param mobxDatas
   * @returns {Promise<any>}
   */
  changeDocPublishType = (field, mobxDatas) => {
    return new Promise((resolve => {
      resolve();
      let publishType = toJS(mobxDatas);
      // 页面显示的处理在组件里做了，这里只负责切换时的清空数据
      if (publishType !== '2') {
        this.form.updateField('docmain', '');
      }
    }));
  }
  
  /**
   * 返回 回复表情组件的更多设置
   * @returns {Promise<any>}
   */
  getReplyAttachList = () => {
    let browserConfig = {
      type: 'browser',
      path: `${this.path}/browser`,
      model: 2, // model(模式) 1: 常规模式， 2: 编辑模式（不显示小红点）
    };
    const attachList = [
      {
        ...browserConfig,
        key: 'workflow', // 字符串
        config: {
          type: 152,
          isSingle: false,
          hasAdvanceSerach: true,
        },
        iconType: 'flow',
        iconBgColor: '#61A8F5',
        text: getLabel(30045, '流程'),
      },
      {
        ...browserConfig,
        key: 'doc',
        config: {
          type: 37,
          isSingle: false,
        },
        iconType: 'file',
        iconBgColor: '#F3B04C',
        text: getLabel(22243, '文档'),
      },
      {
        ...browserConfig,
        key: 'customer',
        config: {
          type: 18,
          isSingle: false,
        },
        iconType: 'relevant-customer',
        iconBgColor: '#FB8D00',
        text: getLabel(136, '客户'),
      },
      {
        ...browserConfig,
        key: 'project',
        config: {
          type: 135,
          isSingle: false,
        },
        iconType: 'relevant-project',
        iconBgColor: '#009EFB',
        text: getLabel(101, '项目'),
      },
      {
        ...browserConfig,
        key: 'task',
        config: {
          type: 'prjtsk',
          isSingle: false,
        },
        iconType: 'related-tasks',
        iconBgColor: '#7FACBA',
        text: getLabel(1332, '任务'),
      },
      {
        key: 'file',
        type: 'upload',
        path: `${this.path}/upload`,
        config: {
          multiSelection: true,
          limitType: this.uploadType,
          maxUploadSize: this.uploadSize,
        },
        iconType: 'enclosure',
        iconBgColor: '#57D58F',
        text: getLabel(156, '附件'),
        model: 1
      },
    ];
    return new Promise(resolve => resolve({attachList}));
  }
  
  /**
   * 记录 回复表情组件的ref
   * @param ref
   */
  // setReplyRef = (ref) => {
  //   this.replyRef = ref;
  // }
  
  /**
   * 初始化共享页面
   */
  initShare = () => {
    if (!this.id) {
      return;
    }
    this.getShareList();
    API.shareCanEdit({id: this.id}).then((result) => {
      this.shareCanAdd = result.hasAddBtn === '1';
      this.shareCanDelete = result.hasDelBtn === '1';
    });
    API.getShareCondition({docid: this.id}).then((result) => {
      this.shareCondition = result.conditions;
    });
  }
  getShareList = () => {
    API.shareList({id: this.id}).then((result) => {
      this.defaultShareList = result.defaultShareList;
      this.nonDefaultShareList = result.nonDefaultShareList;
    });
  }
  
  /**
   * 删除共享
   * @param shareId
   */
  delShare = (shareId) => {
    alert(getLabel(131329,'信息确认'), getLabel(388758,'确认要删除吗？'),
      [
        { text: getLabel(31129, '取消')},
        {
          text: getLabel(826, '确定'),
          onPress: () => {
            API.deleteShare({docid: this.id, shareId: shareId}).then((result) => {
              this.getShareList();
            })
          }
        },
      ]);
  }
  
  /**
   * 新增共享
   * @param params
   */
  addShare = (params) => {
    if(params.objType==2&&params.subcompany!=undefined&&params.subcompanyspan!=undefined){
      params.obj_id=params.subcompany;
      params.obj_idspan=params.subcompanyspan;
    }
      if(params.objType==3&&params.department!=undefined&&params.departmentspan!=undefined){
        params.obj_id=params.department;
        params.obj_idspan=params.departmentspan;
      }
    API.saveShare({...params, id: this.id}).then(() => {
      this.getShareList();
    })
  }
  
  /**
   * 共享提交
   * @param history
   */
  afterSave = (history) => {
    API.afterSave({id: this.id}).then((result) => {
      if (isFunction(this.saveBackFunc)) {
        this.saveBackFunc({id: this.id, history});
      }
    });
  }
}